/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.User;
import org.hibernate.Session;
import service.HibernateUtil;
import service.UserDao;

/**
 *
 * @author Serife
 */
public class EmailTeachersController extends HttpServlet {

    private HibernateUtil HU = new HibernateUtil();
    private Session sessie = HU.openSession();
    private UserDao ud = new UserDao(sessie);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        HttpSession sessie = request.getSession(true);
        List<User> users = ud.findAll();
        List<User> teachers = new ArrayList<User>();
        for (User currentUser : users) {
            if ("Tutor".equals(currentUser.getStatus())) {
                teachers.add(currentUser);
            }
            // System.out.println(currentUser.getStatus());
        }
        sessie.setAttribute("teachers", teachers);
        forward(request,response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException{
        String teacherEmail = request.getParameter("teacherList");
        String from = request.getParameter("emailFrom");
        String content = request.getParameter("content");
        String subject = request.getParameter("subject");
        EmailController emailControl = new EmailController();
            emailControl.sendEmail(teacherEmail, content, subject);
            String language = models.Bean.getLanguage();
                if (language.equals("nl")) {
                    request.setAttribute("melding", "Je bericht is verzonden. De docent probeert zo spoedig mogelijk te reageren");
                } else {
                    request.setAttribute("melding", "Your message has been send. The teacher will try to answer as soon as possible.");
                }
            forward(request,response);
    }
    
    private void forward(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String address = "/emailToTeacher.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}
